﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Validation.sp2010.Classes;
using System.Globalization;
using System.Collections;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace Validation.sp2010.Layouts.Validation.sp2010
{
    public partial class FormTask : LayoutsPageBase
    {
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            this.MasterPageFile = SPContext.Current.Web.MasterUrl;

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;

            //get current Task

            SPListItem taskValidation = SPContext.Current.ListItem;
            SPWeb web = SPContext.Current.Web;


            bool withExtension = bool.Parse(taskValidation[Constante.FieldGuid.WithExtention].ToString());
            bool forceValidation = bool.Parse(taskValidation[Constante.FieldGuid.ForceValidation].ToString());

            try
            {
                //set FieldIterator options
                SPList list = web.Lists[new Guid(taskValidation[SPBuiltInFieldId.WorkflowListId].ToString())];
                SPListItem item = list.GetItemById((int)taskValidation[SPBuiltInFieldId.WorkflowItemId]);

                ListFieldIterator.ItemId = item.ID;
                ListFieldIterator.ListId = list.ID;
            }
            catch (Exception)
            {
                //Current User cannot view List or ListItem
                ListFieldIterator.Visible = false;
                Error_Iterator.Visible = true;
            }

            Literal_TaskTitle.Text = taskValidation.Title;
            if (taskValidation[SPBuiltInFieldId.Body] != null)
                Literal_TaskDesc.Text = taskValidation[SPBuiltInFieldId.Body].ToString();

            //verify with extesnion
            if (!withExtension)
            {
                Row_nextValidator.Visible = false;
                validateWith.Visible = false;
            }

            //verify force validation
            if (forceValidation)
            {
                refuse.Visible = false;
                validateWith.Visible = false;
            }

            #region Update Controls

            //if the task contain next_validaor field, set the Peopde Editor value
            var val = taskValidation[Constante.FieldGuid.NextValidator];
            if (val != null)
            {
                SPFieldUser field = taskValidation.Fields[Constante.FieldGuid.NextValidator] as SPFieldUser;
                if (field != null)
                {
                    SPFieldUserValue fieldValue =
                     field.GetFieldValue(val.ToString()) as SPFieldUserValue;
                    if (fieldValue != null)
                    {
                        if (fieldValue.User != null)
                        {
                            ValidatorUser.CommaSeparatedAccounts = fieldValue.User.LoginName;
                        }
                        else
                        {
                            ValidatorUser.CommaSeparatedAccounts = fieldValue.LookupValue;
                        }
                    }
                }
            }

            // set comment vale
            val = taskValidation[Constante.FieldGuid.Comment];
            if (val != null)
                comment_TextBox.Text = val.ToString();


            string mode = this.Request.QueryString["mode"];
            if (mode == "Display")//mode display
            {

                ValidatorUser.Enabled = false;
                comment_TextBox.Enabled = false;

                save.Visible = false;
                validate.Visible = false;
                refuse.Visible = false;
                validateWith.Visible = false;

                if (!taskValidation.DoesUserHavePermissions(SPBasePermissions.EditListItems))
                    LinkButton.Visible = false;

            }
            else//EDIT
            {
                if (taskValidation[SPBuiltInFieldId.TaskStatus].ToString() == SPResource.GetString(CultureInfo.GetCultureInfo((int)web.Language), "WorkflowTaskStatusComplete"))
                {
                    //task Completed
                    validate.Visible = false;
                    refuse.Visible = false;
                    validateWith.Visible = false;
                }


                LinkButton.Visible = false;
            }

            #endregion


        }

        protected void Save_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse(null, false, false);
        }

        protected void Validate_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse((CurrentListTask.Fields[Constante.FieldGuid.Response] as SPFieldChoice).Choices[1], true, false);
        }
        protected void Refuse_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse((CurrentListTask.Fields[Constante.FieldGuid.Response] as SPFieldChoice).Choices[2], true, false);

        }

        protected void ValidateWith_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse((CurrentListTask.Fields[Constante.FieldGuid.Response] as SPFieldChoice).Choices[0], true, true);

        }

        private void SetResponse(string response, bool completed, bool validateWith)
        {
            SPListItem taskValidation = SPContext.Current.ListItem;
            SPWeb web = SPContext.Current.Web;

            Hashtable properties = new Hashtable();
            if (response != null)
                properties[Constante.FieldGuid.Response] = response;

            properties[Constante.FieldGuid.Comment] = comment_TextBox.Text;






            if (validateWith)
            {
                if (((PickerEntity)(ValidatorUser.Entities[0])).EntityData["PrincipalType"].ToString() == "User")
                {
                    SPUser nextUser = web.AllUsers[ValidatorUser.Accounts[0].ToString()];
                    SPFieldUserValue nexUserValue = new SPFieldUserValue(web, nextUser.ID, nextUser.Name);

                    properties[Constante.FieldGuid.NextValidator] = nexUserValue;
                }
                else
                {
                    SPGroup nextGroup = web.Groups[ValidatorUser.Accounts[0].ToString()];
                    SPFieldUserValue nexUserValue = new SPFieldUserValue(web, nextGroup.ID, nextGroup.Name);

                    properties[Constante.FieldGuid.NextValidator] = nexUserValue;
                }
            }


            #region Complete task
            if (completed)
            {
                properties[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(CultureInfo.GetCultureInfo((int)web.Language), "WorkflowTaskStatusComplete");
                properties[SPBuiltInFieldId.PercentComplete] = 1;
            }


            bool oldValueWeb = web.AllowUnsafeUpdates;
            web.AllowUnsafeUpdates = true;
            SPWorkflowTask.AlterTask(taskValidation, properties, false);
            web.AllowUnsafeUpdates = oldValueWeb;
            //if (completed)
            //{
            //    if ((int)taskValidation[SPBuiltInFieldId.WorkflowVersion] != 1)
            //    {
            //        taskValidation[SPBuiltInFieldId.WorkflowVersion] = 1;
            //        taskValidation.Update();
            //    }
            //}


            #endregion

            #region Close task

            if ((SPContext.Current != null) && SPContext.Current.IsPopUI)
            {

                this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                this.Context.Response.Flush();
                this.Context.Response.End();
            }

            else
            {
                string source = this.Request.QueryString["Source"];
                if (!string.IsNullOrEmpty(source))
                {
                    this.Response.Redirect(source);
                }
                else
                    this.Response.Redirect(SPContext.Current.Web.Url);
            }
            #endregion
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            SPListItem taskValidation = SPContext.Current.ListItem;
            Response.Redirect(taskValidation.ParentList.DefaultEditFormUrl + "?ID=" + taskValidation.ID + "&IsDlg=1", true);

        }
    }
}
